package com.ws.shop.action.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ws.shop.entity.Accessory;
import com.ws.shop.entity.Packagz;
import com.ws.shop.service.AccessoryService;
import com.ws.shop.service.PackagzService;
import com.ws.shop.util.RequestUtil;

@Controller
@RequestMapping(value="/admin/packagz/*")
public class PackagzAction extends BaseAdminAction{
	private static Logger log = Logger.getLogger(PackagzAction.class);
	@Autowired
	private PackagzService packagzService;
	@Autowired
	private AccessoryService accessoryService;

	@RequestMapping(value="index.jhtml",method=RequestMethod.GET)
	public String index(HttpServletRequest request,Model model){
		List<Packagz> packageList = packagzService.findListAll();
		model.addAttribute("packageList", packageList);
		return "packagz_index";
	}
	
	@RequestMapping(value="input.jhtml",method=RequestMethod.GET)
	public String input(HttpServletRequest request,Model model){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		if(id > 0){
			Packagz packagz = packagzService.findPackagzById(id);
			if(packagz == null){
				model.addAttribute(ERROR_MSG, "您选择的套餐不存在");
				return ERROR;
			}
			Accessory accessory = accessoryService.findAccessoryById(packagz.getPath());
			model.addAttribute("packagz", packagz);
			model.addAttribute("accessory", accessory);
		}
		model.addAttribute("saveImagUrl",AccessoryAction.SAVE_IMAG_URL);
		model.addAttribute("id", id);
		return "packagz_input";
	}
	
	@RequestMapping(value="save.jhtml",method=RequestMethod.POST)
	public String save(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request, "id", 0);
		int amount = RequestUtil.getIntParameter(request, "amount", 0);
		int beat = RequestUtil.getIntParameter(request, "beat", 0);
		int pointb = RequestUtil.getIntParameter(request, "pointb", 0);
		int path = RequestUtil.getIntParameter(request, "path", 0);
		Packagz packagz = new Packagz(id, amount, beat, pointb, 0,path);
		try{
			packagzService.saveOrUpdate(packagz);
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+packagz,e);
			return this.ajaxJsonErrorMessage(response, "系统异常，请稍后再试");
		}
	}
	
}
